import {Directive, forwardRef} from '@angular/core';
import {NG_VALIDATORS, Validator, AbstractControl, Validators} from "@angular/forms";
import {ValidatorRegexPattern} from "./validator-regex-pattern";

@Directive({
  selector: '[cnZip][formControlName],[cnZip][formControl],[cnZip][ngModel]',
  providers: [
    {provide: NG_VALIDATORS, useExisting: forwardRef(() => CnZipValidator), multi: true}
  ]
})
export class CnZipValidator implements Validator {
  validate(c: AbstractControl): { [key: string]: any } {
    if (Validators.required(c) != undefined) {
      return null;
    }

    let value = c.value;
    if (!value) {
      return null;
    }

    let isValid = ValidatorRegexPattern.chinaZipCode.test(value);

    return isValid ? null : {
      cnZip: {
        valid: false
      }
    };
  }
}
